package com.xia.netty.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class BioServer {
    public static void main(String[] args) throws Exception {
        //监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);

        //轮询
        while (true) {
            //接收客户端连接 accept是阻塞的
            Socket accept = serverSocket.accept();
            new Thread(new ServerHandler(accept)).start();

        }

    }

    static class ServerHandler implements Runnable {
        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

                while (true) {
                    String line = bufferedReader.readLine();
                    System.out.println("接收到客户端数据: " + line);

                    //向服务端写回数据
                    bufferedWriter.write("返回客户端的数据 \n");
                    //BufferedWriter中的write方法写的数据在缓冲区,需要调用flush写回文件
                    bufferedWriter.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        private final Socket socket;

        public ServerHandler(Socket socket) {
            this.socket = socket;
        }

    }


}
